# -*- coding: utf-8 -*-
import threading
import time
from tkinter import *

from ai.ai import ai
from event.event_bus import event_bus

from PIL import ImageTk,Image
  
class main_class(object):

    def reply_msg(self,reply):
        self.txt_msg_list.config(state=NORMAL)
        str_msg = "助理:" + time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) + '\n'
        self.txt_msg_list.insert(END, str_msg, 'redcolor')
        self.txt_msg_list.insert(END, reply)
        self.txt_msg_list.insert(END, "\n\n")
        self.txt_msg_list.see(END)
        self.txt_msg_list.config(state=DISABLED)
        # self.txt_msg_list.tag_add('link', '1.0','1.16')

    def send_msg(self):  # 发送消息
        self.txt_msg_list.config(state=NORMAL)
        input_str = self.txt_msg.get('0.0', END)
        str_msg = "我:" + time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) + '\n'
        self.txt_msg_list.insert(END, str_msg, 'greencolor')
        self.txt_msg_list.insert(END, input_str)
        self.txt_msg_list.insert(END, "\n")
        self.txt_msg_list.config(state=DISABLED)

        reply = self.m_ai.get_reply(input_str=input_str) #通过输入获取相应的输出

        try:
            self.reply_msg(reply)

            thrd_once = threading.Thread(target=self.drop_return)
            thrd_once.start()
        except Exception as e:
            print(e)

    def drop_return(self):
        time.sleep(0.01)
        self.txt_msg.delete('0.0', END)

    def cancel_msg(self):  # 取消信息
        self.txt_msg.delete('0.0', END)

    def close_msg(self):  # 关闭消息
        event_bus().unregister(self)
        self.app.destroy()

    def send_msg_event(self,event):  # 发送消息事件
        self.send_msg()

    def event_bus_callback(self,type,msg):
        print("type=%s,msg=%s" % (type,msg))
        if type == "assist":
            if msg == "退出":
                self.close_msg()

        pass

    def on_closing(self):
        self.close_msg()
        pass

    def text_click(self,event):
        print(event)
        pass

    def show_arrow_cursor(self,event):
        self.txt_msg_list.config(cursor='arrow')
        pass

    def show_xterm_cursor(self,event):
        self.txt_msg_list.config(cursor='xterm')
        pass

    def __init__(self):
        # 创建窗口
        self.app = Tk()        
        self.app.title('与助理聊天')
        self.app.resizable(0,0) #防止用户调整尺寸
        self.app.attributes("-toolwindow", 1)

        #注册evenbus
        event_bus().register(self)

        # 创建frame容器
        self.left_width = 600
        self.right_width = 350
        self.frm_left_output = Frame(width=self.left_width, height=320, bg='white')
        self.frm_left_input = Frame(width=self.left_width, height=150, bg='white')
        self.frm_left_button_group = Frame(width=self.left_width, height=30)
        self.frm_right = Frame(width=self.right_width, height=500)

        # 创建滚动条
        scroll = Scrollbar(self.frm_left_output)

        # 创建控件
        self.txt_msg_list = Text(self.frm_left_output,spacing3=0,yscrollcommand=scroll.set,  wrap='none')
        self.txt_msg_list.tag_config('greencolor', foreground='#008C00')  # 创建tag，用于设定自己的颜色
        self.txt_msg_list.tag_config('redcolor', foreground='#ff0000')  # 创建tag，用于设定对方的颜色
        self.txt_msg_list.tag_config('link', foreground='blue', underline=True)
        self.txt_msg_list.tag_bind('link', '<Button-1>', self.text_click)
        self.txt_msg_list.tag_bind('link', '<Enter>', self.show_arrow_cursor)
        self.txt_msg_list.tag_bind('link', '<Leave>', self.show_xterm_cursor)
        self.txt_msg_list.config(state=DISABLED)
        self.txt_msg = Text(self.frm_left_input)
        self.txt_msg.bind("<Key-Return>", self.send_msg_event)
        scroll.config(command=self.txt_msg_list.yview)  # 将文本框关联到滚动条上，滚动条滑动，文本框跟随滑动

        self.btn_send = Button(self.frm_left_button_group, text='发送', width=8, command=self.send_msg)
        self.btn_cancel = Button(self.frm_left_button_group, text='清空', width=8, command=self.cancel_msg)
        self.btn_close = Button(self.frm_left_button_group, text='关闭', width=8, command=self.close_msg)
        # 右侧图片 需要可取消注释
        self.img_info = ImageTk.PhotoImage(Image.open("assistant.jpg").resize((350, 600)))
        self.lbl_image = Label(self.frm_right, image=self.img_info)
        self.lbl_image.image = self.img_info

        # 窗口布局
        self.frm_left_output.grid(row=0, column=0, columnspan=2, padx=1, pady=3)
        self.frm_left_input.grid(row=1, column=0, columnspan=2, padx=1, pady=3)
        self.frm_left_button_group.grid(row=2, column=0, columnspan=2)
        self.frm_right.grid(row=0, column=2, rowspan=3, padx=2, pady=3)

        # 固定大小
        self.frm_left_output.grid_propagate(0)
        self.frm_left_input.grid_propagate(0)
        self.frm_left_button_group.grid_propagate(0)
        self.frm_right.grid_propagate(0)

        self.btn_send.grid(row=2, column=0)
        self.btn_cancel.grid(row=2, column=1)
        self.btn_close.grid(row=2, column=3)
        self.lbl_image.grid() 
        self.txt_msg_list.grid()
        scroll.grid(row=0,column=1,sticky='ns')
        self.txt_msg.grid()


        #初始化ai
        self.m_ai = ai()
        self.m_ai.load_data()

        # 主事件循环
        self.app.protocol("WM_DELETE_WINDOW", self.on_closing)
        self.app.mainloop()


if __name__ == "__main__":
    main_class()
